<?php

namespace Iwester\Http\Controllers\Admin\Spider;

use Iwester\Http\Controllers\Admin\BaseController;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Iwester\Http\Model\Article\ArticleCategory;
use Iwester\Http\Model\Spider\SpiderArticleContent;
use Iwester\Http\Model\Spider\SpiderTask;
use Iwester\Http\Model\Spider\SpiderTaskConfig;
use Iwester\Services\FunctionService;
use Iwester\Services\SpiderService;
use phpDocumentor\Reflection\Types\Collection;
use QL\QueryList;
use Symfony\Component\Translation\Tests\Writer\BackupDumper;
use View;
use Iwester\Http\Model\Config\Banner;


class AdminSpiderController extends BaseController
{
    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

    public function test(){
        $a = new SpiderService();
        $a->spider();
    }

    /**
     * 采集任务 列表
     * @return Response
     */
    public function task(Request $request)
    {
        $tasks = SpiderTask::with(['listConfig','listArticle'])->orderBy('status', 'desc')->orderBy('created_at', 'desc')->paginate(20);
        return view('iwester::admin.spider.task', [
            'tasks'=> $tasks,
            'params'=> $request->all()
        ]);
    }

    /**
     * 添加文章采集任务
     * @param int $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function taskArticleCreate($id=0)
    {
        $task = $id ?  $tasks = SpiderTask::with('listConfig')->where('id', $id)->first() : false;
        $categories = ArticleCategory::allCategory();
        return view('iwester::admin.spider.create', [
            'task'=> $task,
            'categories'=> $categories,
        ]);
    }



    /**
     * 测试文章列表页抓取
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function testArticlelist(Request $request)
    {
        try {
            $taskParams = $request->get('task', []);
            $cookie = $taskParams['cookie'];
            $listParams = $request->get('config', []);
            $charset = SpiderTask::$charsets[$taskParams['charset']];
            $pageUrl = $listParams['list_url'];
            $pageUrl = str_replace(SpiderTask::PAGE, 1, $pageUrl);
            $html = SpiderService::getHtml($pageUrl, $cookie);
            # 1: 分析分页页码
            $maxPage = SpiderService::formatPageParam($html, $listParams['list_page_param']);
            # 2：测试列表页请求
            $listDatas = SpiderService::testListQuery($html, $listParams);
            return ['code' => 200, 'maxPage'=> $maxPage, 'testPage'=> $pageUrl, 'testData'=> $listDatas];
        } catch (\Exception $e) {
            return  ['code'=> 201, 'message'=> '测试失败 - '.$e->getMessage()];
        }
    }

    /**
     * 测试文章详情页抓取
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function testDetai(Request $request)
    {
        try {
            $taskParams = $request->get('task', []);
            $cookie = $taskParams['cookie'];
            $detailParams = $request->get('detail', []);
            $pageUrl = $detailParams['detail_test_url'];
            $result = SpiderService::detail($pageUrl, $detailParams, $cookie);
            return ['code' => 200, 'testPage'=> $pageUrl, 'testData'=> collect($result)];
        } catch (\Exception $e) {
            return  ['code'=> 201, 'message'=> '测试失败'];
        }
    }

    /**
     * 保存配置数据
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function taskArticleStore(Request $request){
        try {
            \DB::beginTransaction();
            $id = $request->get('id', 0);
            $taskParams = $request->get('task', []);
            $listParams = $request->get('config', []);
            $detailParams = $request->get('detail', []);

            if ($id){
                $task = SpiderTask::find($id);
                if ($task->freq != $taskParams['freq']){
                    $taskParams['next_spider_time'] = Carbon::now()->addHour(SpiderTask::$freqHours[$taskParams['freq']]);
                }
                $task->update($taskParams);
                $spiderTaskConfig = $task->listConfig;
            }else{
                $taskParams['next_spider_time'] = Carbon::now()->addHour(SpiderTask::$freqHours[$taskParams['freq']]);
                $task = SpiderTask::create($taskParams);
            }
            $listSaveParams = [
                'task_id'=> $task->id,
                'list_url'=> $listParams['list_url'],
                'table_template'=> $listParams['table_template'],
                'list_page_matche'=> $listParams['list_page_param']['rule'],
                'list_page_attr'=> $listParams['list_page_param']['type'],
                'list_url_content'=> json_encode($listParams['list_param']),
                'detail_use_page'=> $detailParams['detail_use_page'],
                'detail_page_url'=> $detailParams['fenye_url'],
                'detail_page_matche'=> $detailParams['detail_use_page'] == 1 ? $detailParams['page_param']['rule'] : '',
                'detail_page_attr'=> $detailParams['detail_use_page'] == 1 ? $detailParams['page_param']['type']: '',
                'detail_url_content'=> json_encode($detailParams['data_param']),
            ];
            if ($id){
                $spiderTaskConfig->update($listSaveParams);
            }else{
                SpiderTaskConfig::create($listSaveParams);
            }
            \DB::commit();
            return ['code' => 200, 'message'=> '保存成功' , 'href'=> route('spider.task')];
        } catch (\Exception $e) {
            \DB::rollBack();
            return  ['code'=> 201, 'message'=> '系统错误，保存失败'];
        }
    }

    /**
     * 删除
     * @param $id
     * @return array
     * @throws \Exception
     */
    public function destroy($id)
    {
        try {
            \DB::beginTransaction();
            $task = SpiderTask::find($id);
            $task->status = 0;
            $task->save();
            \DB::commit();
            return ['code' => 200, 'message' => '删除成功！'];
        } catch (\Exception $e) {
            \DB::rollBack();
            return ['code' => 201, 'message' => $e->getMessage()];
        }
    }
}
